package top.maybesix.base.base

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.ViewGroup
import android.view.Window
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import top.maybesix.base.action.BundleAction
import top.maybesix.base.action.ClickAction
import top.maybesix.base.action.HandlerAction
import java.util.*

/**
 * @author MaybeSix
 * @date 2020/3/18
 * @desc TODO.
 */
abstract class BaseActivity : AppCompatActivity(),
    IActivity, HandlerAction, ClickAction, BundleAction {
    override fun onCreate(savedInstanceState: Bundle?) {
        // 在界面未初始化之前调用的初始化窗口
        initWidows()
        super.onCreate(savedInstanceState)
        initActivity()

    }

    private fun initActivity() {
        initLayout()
        initBefore()
        initView()
        initEvent()
        initAdapter()
        initListener()
        initData()
    }

    /**
     * 初始化布局
     */
    protected open fun initLayout() {
        if (getLayoutId() > 0) {
            setContentView(getLayoutId())
            initSoftKeyboard()
        }
    }

    /**
     * 初始化软键盘
     */
    protected open fun initSoftKeyboard() {
        // 点击外部隐藏软键盘，提升用户体验
        getContentView()?.setOnClickListener { hideSoftKeyboard() }
    }

    override fun onDestroy() {
        super.onDestroy()

    }

    override fun finish() {
        hideSoftKeyboard()
        super.finish()
    }

    /**
     * 如果当前的 Activity（singleTop 启动模式） 被复用时会回调
     */
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        // 设置为当前的 Intent，避免 Activity 被杀死后重启 Intent 还是最原先的那个
        setIntent(intent)

    }

    override fun getBundle(): Bundle? {
        return intent.extras
    }

    override fun getHandler(): Handler {
        return Handler(Looper.getMainLooper())
    }

    /**
     * 获取当前 Activity 对象
     */
    protected open fun getActivity(): BaseActivity {
        return this
    }

    /**
     * 和 setContentView 对应的方法
     */
    open fun getContentView(): ViewGroup? {
        return findViewById(Window.ID_ANDROID_CONTENT)
    }

    /**
     * startActivity 方法简化
     */
    open fun startActivity(clazz: Class<out Activity?>?) {
        startActivity(Intent(this, clazz))
    }

    /**
     * startActivityForResult 方法优化
     */
    private var mActivityCallback: OnActivityCallback? = null
    private var mActivityRequestCode = 0

    open fun startActivityForResult(
        clazz: Class<out Activity>,
        callback: OnActivityCallback?
    ) {
        startActivityForResult(Intent(this, clazz), null, callback)
    }

    open fun startActivityForResult(
        intent: Intent?,
        callback: OnActivityCallback?
    ) {
        startActivityForResult(intent, null, callback)
    }

    open fun startActivityForResult(
        intent: Intent?,
        options: Bundle?,
        callback: OnActivityCallback?
    ) {
        // 回调还没有结束，所以不能再次调用此方法，这个方法只适合一对一回调，其他需求请使用原生的方法实现
        if (mActivityCallback == null) {
            mActivityCallback = callback
            // 随机生成请求码，这个请求码必须在 2 的 16 次幂以内，也就是 0 - 65535
            mActivityRequestCode = Random().nextInt(Math.pow(2.0, 16.0).toInt())
            startActivityForResult(intent, mActivityRequestCode, options)
        }
    }

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        if (mActivityCallback != null && mActivityRequestCode == requestCode) {
            mActivityCallback!!.onActivityResult(resultCode, data)
            mActivityCallback = null
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

    override fun startActivityForResult(
        intent: Intent?,
        requestCode: Int,
        options: Bundle?
    ) {
        hideSoftKeyboard()
        // 查看源码得知 startActivity 最终也会调用 startActivityForResult
        super.startActivityForResult(intent, requestCode, options)
    }

    /**
     * 隐藏软键盘
     */
    private fun hideSoftKeyboard() {
        // 隐藏软键盘，避免软键盘引发的内存泄露
        val view = currentFocus
        if (view != null) {
            val manager =
                getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            manager.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

    interface OnActivityCallback {
        /**
         * 结果回调
         *
         * @param resultCode        结果码
         * @param data              数据
         */
        fun onActivityResult(resultCode: Int, data: Intent?)
    }
}